package com.we823.cms.repository.service.beetl.tag;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.we823.cms.model.extension.ProductCategory;
import com.we823.cms.repository.service.extension.ProductCategoryService;

@Service("cms_product_categories")
@Scope("prototype")
public class ProductCategoryListTag extends AbstractListTag {

	private static final String PARAM_PARENTID = "parentid";

	@Autowired
	private ProductCategoryService productCategoryService;
	
	@Override
	public void execute() {
		int parentid = getParam(PARAM_PARENTID, 0);
		List<ProductCategory> productCategoryModels = null;
		if (parentid == -1) {
			productCategoryModels = productCategoryService.findAll(sort);
		} else {
			if (pageRequest == null) {
				productCategoryModels = productCategoryService.findByParentid(parentid, sort);
			} else {
				PageInfo<ProductCategory> productCategoryPage = productCategoryService.findByParentid(parentid, pageRequest);
				if (productCategoryPage != null) {
					productCategoryModels = productCategoryPage.getList();
				}
			}
		}

		if (productCategoryModels != null) {
			List<ProductCategory> productCategorys = productCategoryService.findAll();
			Map<Integer, List<ProductCategory>> map = getMap(productCategorys);
			for (ProductCategory productCategoryModel : productCategoryModels) {
				List<ProductCategory> children = map.get(productCategoryModel.getId());
				productCategoryModel.setChilds(children);
			}
		}
		
		this.binds(productCategoryModels);

	}

	private Map<Integer, List<ProductCategory>> getMap(List<ProductCategory> productCategorys) {
		Map<Integer, List<ProductCategory>> map = new HashMap<Integer, List<ProductCategory>>();
		if (productCategorys != null) {
			for (ProductCategory productCategoryModel : productCategorys) {
				ProductCategory parent = productCategoryModel.getParent();
				int parentid = 0;
				if (parent != null) {
					parentid = parent.getId();
				}
				List<ProductCategory> children = map.get(parentid);
				if (children == null) {
					children = new ArrayList<>();
					children.add(productCategoryModel);
					map.put(parentid, children);
				} else {
					children.add(productCategoryModel);
				}
			}
		}
		return map;
	}
	
	public ProductCategoryService getProductCategoryService() {
		return productCategoryService;
	}

	public void setProductCategoryService(
			ProductCategoryService productCategoryService) {
		this.productCategoryService = productCategoryService;
	}

	
}
